
import React, { useRef, useState, useEffect } from "react"
import { ConfigProvider, Empty, Table, Button, Space, Pagination } from "antd"
import "./zcTable.scss"
import Tablepanel from "./tabblePanel";
import Notfound from "../../component/notFound/not-found";


/**
 * @author 韩
 * @param {*} param0 
 * @returns 
 * @desc API说明：size 为表格尺寸

 */


const XxTableModel = ({
  hideActionPanel = false,
  selectRecords = [],
  tablePanelConfig = [],
  showAllRows,
  dataSource = [],
  scroll = {},
  createClick = () => { },
  pagination,
  size = "small",
  loading = false,
  columns = [],
  rowSelection = Object,
  ...props
}) => {

  // props
  const {
    onRowClick: oneClick,
    onRowDoubleClick: doubleClick,
    rowKey = "_id",
    type = 'check'
  } = props



  const [useColumns, setUseColumns] = useState([columns]);
  useEffect(() => {
    setUseColumns(columns)
  }, [columns])

  // const fiterColumns = props.columns.filter(item => !item.hideConfig)
  const { deductHeight = 0 } = props // 允许组件外部手动扣除一定高度
  // 获取widnow高宽
  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  })

  const [windowSize, setWindowSize] = useState(getWindowSize())

  const handleResize = () => {
    // console.log(getWindowSize())
    setWindowSize(getWindowSize())
  }
  // 监听窗口变化，重新获取windowSize
  useEffect(() => {
    window.addEventListener('resize', handleResize)
    //卸载组件的时候销毁resize监听事件
    return () => window.removeEventListener('resize', handleResize)
  }, [])
  const [scrollY, setScrollY] = useState()
  const [clientTop, setClientTop] = useState(0)
  // 根据页面高度动态设置表格垂直出现滚动的高度
  const tabCenterRef = useRef();
  const setScrollYFun = () => {

    if (tabCenterRef.current.getBoundingClientRect().top) {
      const winClientTop = tabCenterRef.current.getBoundingClientRect().top
      setClientTop(winClientTop)
      setScrollY((preScrollY) => {
        // console.log('showAllRows',showAllRows)
        if (showAllRows) {
          return 'max-content'
        }
        // 表格高度 = 页面高度 - 表格元素距离顶部距离 - 固定值 - 扣除高度
        // console.log(windowSize.innerHeight,winClientTop,)
        return windowSize.innerHeight - winClientTop - deductHeight
      })
    } else {
      setScrollY((preScrollY) => {
        if (showAllRows) {
          return 'max-content'
        }
        // 表格高度 = 页面高度 - 表格元素距离顶部距离 - 固定值 - 扣除高度
        return windowSize.innerHeight - clientTop - deductHeight
      })
    }
  }

  useEffect(() => {
    // 页面元素还没有创建完成，使用延迟加载
    if (tabCenterRef.current.getBoundingClientRect().top) {
      setScrollYFun()
    } else {
      setTimeout(() => {
        setScrollYFun()
      }, 30)
    }
  }, [windowSize])
  /**
   * 表格事件
   *  onClick：单击
   *  onDoubleClick：双击
   *  onContextMenu：右击
   *  onMouseEnter：鼠标移入行
   *  onMouseLeave：鼠标移出行
   */
  // const onRow = onRowEvent
  const onRow = (record, index) => {
    return {
      onClick: (e) => {
        if (oneClick) {
          oneClick(record, index)
        }
      },
      onDoubleClick: (e) => {
        if (doubleClick) {
          doubleClick(record, index)
        }
      },
      onContextMenu: (e) => { },
      onMouseEnter: (e) => { },
      onMouseLeave: (e) => { },
    }
  }

  const tabRef = useRef()
  // useEffect(() => {
  //   // if(scrollY){
  //   const div = tabRef.current
  //   if (div) {
  //     // console.log("146打印下div", div)
  //     div.style.height = '100%'
  //     const scroHeight = dataSource.length > 0 ? 0 : 0

  //     const tableLoading = document.getElementsByClassName('ant-spin-nested-loading')[0]

  //     if (tableLoading) {
  //       tableLoading.style.height = '100%'
  //     }

  //     const tableSpinContainer = document.getElementsByClassName('ant-spin-container')[0]
  //     if (tableSpinContainer) {
  //       if (dataSource.length === 0) {
  //         tableSpinContainer.style.display = null
  //         tableSpinContainer.style.flexDirection = null
  //         tableSpinContainer.style.height = '100%'
  //       } else {
  //         tableSpinContainer.style.display = "flex"
  //         tableSpinContainer.style.flexDirection = "column"
  //       }
  //     }

  //     const emptyTable = document.getElementsByClassName('ant-table ant-table-empty')[0]
  //     if (emptyTable) {
  //       emptyTable.style.height = '100%'
  //     }

  //     const tableOuter = div.getElementsByClassName('ant-table ant-table-fixed-header')[0]
  //     if (tableOuter) {
  //       tableOuter.style.height = '100%'
  //     }

  //     const tableContainer = div.getElementsByClassName('ant-table-container')[0]
  //     if (tableContainer) {
  //       tableContainer.style.height = '100%'
  //     }

  //     const tableContent = div.getElementsByClassName('ant-table-content')[0]
  //     if (tableContent) {
  //       const table = tableContent.getElementsByTagName('table')[0]
  //       if (table) {
  //         if (dataSource?.length === 0) {
  //           table.style.height = '100%'
  //         } else {
  //           table.style.height = null
  //         }
  //       }
  //     }

  //     const tableBody = div.getElementsByClassName('ant-table-body')[0]
  //     if (tableBody) {
  //       //
  //       const container = div.getElementsByClassName('ant-table-container')[0]
  //       const containerHeight = container.offsetHeight

  //       //
  //       const header = div.getElementsByClassName('ant-table-header')[0]
  //       const headerHeight = header.offsetHeight

  //       const bodyHeight = containerHeight - headerHeight
  //       tableBody.style.maxHeight = `${bodyHeight - 1 - scroHeight}px`
  //       tableBody.style.height = `${bodyHeight - 1 - scroHeight}px`
  //       // 这里又不对了？
  //       const table = tableBody.getElementsByTagName('table')[0]
  //       if (table) {
  //         if (dataSource?.length === 0) {
  //           table.style.height = '100%'
  //         } else {
  //           table.style.height = null
  //         }
  //       }
  //     }
  //   }

  // }, [dataSource, scrollY])



  return (
    <>


      <ConfigProvider renderEmpty={Notfound}>
        {
          hideActionPanel ? null : <Tablepanel
            columns={columns} //原始配置
            useColumns={useColumns} //真正使用的
            setUseColumns={setUseColumns}
            selectRecords={selectRecords}
            tablePanelConfig={tablePanelConfig} />
        }

        <div className="zc-table-container">
          <div className="tab-center" ref={tabCenterRef}>
            <Table
              ref={tabRef}
              loading={loading}
              scroll={{ ...scroll, y: scroll.y || scrollY }}
              pagination={false}
              columns={useColumns}
              dataSource={dataSource}
              size={windowSize.innerWidth < 1600 ? 'small' : 'default'}
              bordered={true}
              onRow={onRow}
              {...props}
              rowKey={rowKey}
              rowSelection={rowSelection ? {
                checkStrictly: false, //checkable 状态下节点选择完全受控（父子数据选中状态不再关联）
                // type: type,
                ...rowSelection,
              } : null}
            />

          </div>
        </div>
        <div
          style={{
            display: "flex",
            justifyContent: "flex-end",
            padding: "10px 0"
          }}
        >
          {
            pagination && <Pagination  {...pagination} />
          }

        </div>
      </ConfigProvider >

    </>

  )
}
export default XxTableModel;